//
//  MyiOSView.swift
//  Runner
//
//  Created by liuhc on 2023/4/13.
//


import Foundation
import Flutter

class MyiOSView: NSObject,FlutterPlatformView {
    
    private let uiButton = UIButton(type: .custom)
    private let methodChannel:FlutterMethodChannel
    
    init(
        frame: CGRect,
        viewID: Int64,
        args :Any?,
        messenger :FlutterBinaryMessenger
    ) {
        methodChannel = FlutterMethodChannel(name: "pluginChannel", binaryMessenger: messenger)
        super.init()
        methodChannel.setMethodCallHandler { flutterMethodCall, flutterResult in
            if(flutterMethodCall.method == "plugin"){
                self.uiButton.setTitle("iOS接收到的数据：" + (flutterMethodCall.arguments as? String ?? ""), for: .normal)
                flutterResult("iOS received")
            } else {
                flutterResult(FlutterMethodNotImplemented)
            }
        }
        uiButton.backgroundColor = UIColor.systemBlue
        uiButton.setTitleColor(UIColor.black, for: .normal)
        uiButton.layer.borderColor = UIColor.black.cgColor
        uiButton.layer.borderWidth = 1
        uiButton.layer.cornerRadius = 8
        uiButton.addTarget(self, action: #selector(clickEvent), for: .touchUpInside)
        if(args is NSDictionary){
            let dict = args as! NSDictionary
            let initText = dict.value(forKey: "initText") as! String
            uiButton.setTitle("iOS接收到的数据："+initText, for: .normal)
        } else {
            uiButton.setTitle("空数据", for: .normal)
        }
    }
    
    func view() -> UIView {
        return uiButton
    }
    
    @objc func clickEvent() {
        methodChannel.invokeMethod("plugin", arguments: "send from iOS") { result in
            self.uiButton.setTitle("iOS接收到的数据：" + (result as? String ?? ""), for: .normal)
        }
    }
}



